// ============================================================================
// 编辑定时任务模态框组件
// ============================================================================

import React, { useState, useEffect } from 'react'
import { schedulerService, UpdateScheduledTaskOptions } from '../services/scheduler-service'
import { ScrapeTask, ScheduledTaskParams, WeiboLoginData } from '../../shared/types'
import { useNotifications } from '../hooks/use-notifications'
import { logger } from '../utils/logger'

interface EditTaskModalProps {
  task: ScrapeTask
  accounts: WeiboLoginData[]
  onClose: () => void
  onSuccess: () => void
}

/**
 * 编辑定时任务模态框组件
 */
export const EditTaskModal: React.FC<EditTaskModalProps> = ({
  task,
  accounts,
  onClose,
  onSuccess
}) => {
  const [formData, setFormData] = useState({
    keywords: '',
    interval: '30', // 分钟
    maxPages: '3',
    enabled: true
  })
  const [loading, setLoading] = useState(false)
  const { showSuccess, showError } = useNotifications()

  // 初始化表单数据
  useEffect(() => {
    const params = task.params as ScheduledTaskParams
    setFormData({
      keywords: params.keywords.join(', '),
      interval: String(Math.floor(params.interval / (1000 * 60))), // 转换为分钟
      maxPages: String(params.maxPages || 3),
      enabled: params.enabled
    })
  }, [task])

  /**
   * 处理表单提交
   */
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (loading) return

    try {
      setLoading(true)

      // 验证表单
      if (!formData.keywords.trim()) {
        showError('请输入关键字', '')
        return
      }

      // 解析关键字
      const keywords = formData.keywords
        .split(/[,，\n]/)
        .map(k => k.trim())
        .filter(k => k.length > 0)

      if (keywords.length === 0) {
        showError('请输入有效的关键字', '')
        return
      }

      // 构建更新选项
      const updates: UpdateScheduledTaskOptions = {
        keywords,
        interval: parseInt(formData.interval) * 60 * 1000, // 转换为毫秒
        maxPages: parseInt(formData.maxPages),
        enabled: formData.enabled
      }

      // 更新任务
      await schedulerService.updateScheduledTask(task.id, updates)

      showSuccess('定时任务更新成功', '')
      onSuccess()

    } catch (error) {
      logger.error('更新定时任务失败', error)
      showError(
        error instanceof Error ? error.message : '更新任务失败',
        ''
      )
    } finally {
      setLoading(false)
    }
  }

  /**
   * 处理输入变化
   */
  const handleInputChange = (
    field: string,
    value: string | boolean | number
  ) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const params = task.params as ScheduledTaskParams
  const account = accounts.find(acc => acc.id === task.accountId)

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b">
          <h2 className="text-xl font-semibold text-gray-900">编辑定时任务</h2>
          <p className="text-sm text-gray-600 mt-1">
            任务ID: {task.id}
          </p>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* 任务信息 */}
          <div className="bg-gray-50 p-4 rounded-lg">
            <h3 className="text-sm font-medium text-gray-900 mb-2">任务信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-600">使用账号:</span>
                <span className="ml-2 font-medium">
                  {account?.userInfo.nickname || '未知账号'}
                </span>
              </div>
              <div>
                <span className="text-gray-600">创建时间:</span>
                <span className="ml-2">
                  {new Date(task.createdAt).toLocaleString()}
                </span>
              </div>
              <div>
                <span className="text-gray-600">最后执行:</span>
                <span className="ml-2">
                  {params.lastExecuted 
                    ? new Date(params.lastExecuted).toLocaleString()
                    : '未执行'
                  }
                </span>
              </div>
              <div>
                <span className="text-gray-600">下次执行:</span>
                <span className="ml-2">
                  {params.nextExecution 
                    ? new Date(params.nextExecution).toLocaleString()
                    : '未设置'
                  }
                </span>
              </div>
            </div>
          </div>

          {/* 关键字输入 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              关键字 *
            </label>
            <textarea
              value={formData.keywords}
              onChange={(e) => handleInputChange('keywords', e.target.value)}
              placeholder="请输入关键字，多个关键字用逗号或换行分隔"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              rows={3}
              required
            />
            <p className="text-xs text-gray-500 mt-1">
              支持多个关键字，用逗号、中文逗号或换行分隔
            </p>
          </div>

          {/* 执行间隔和最大页数 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                执行间隔（分钟）*
              </label>
              <input
                type="number"
                value={formData.interval}
                onChange={(e) => handleInputChange('interval', e.target.value)}
                min="1"
                max="1440"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              />
              <p className="text-xs text-gray-500 mt-1">
                最小1分钟，最大24小时（1440分钟）
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                最大页数
              </label>
              <input
                type="number"
                value={formData.maxPages}
                onChange={(e) => handleInputChange('maxPages', e.target.value)}
                min="1"
                max="20"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
              <p className="text-xs text-gray-500 mt-1">
                每个关键字最多爬取的页数
              </p>
            </div>
          </div>

          {/* 启用状态 */}
          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.enabled}
                onChange={(e) => handleInputChange('enabled', e.target.checked)}
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="ml-2 text-sm text-gray-700">启用任务</span>
            </label>
            <p className="text-xs text-gray-500 mt-1">
              禁用的任务不会被调度器执行
            </p>
          </div>

          {/* 当前配置预览 */}
          <div className="bg-blue-50 p-4 rounded-lg">
            <h3 className="text-sm font-medium text-blue-900 mb-2">配置预览</h3>
            <div className="text-sm text-blue-800 space-y-1">
              <div>
                关键字数量: {formData.keywords.split(/[,，\n]/).filter(k => k.trim()).length} 个
              </div>
              <div>
                执行间隔: {schedulerService.formatInterval(parseInt(formData.interval) * 60 * 1000)}
              </div>
              <div>
                最大页数: {formData.maxPages} 页/关键字
              </div>
              <div>
                状态: {formData.enabled ? '启用' : '禁用'}
              </div>
            </div>
          </div>

          {/* 按钮 */}
          <div className="flex justify-end space-x-3 pt-4 border-t">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              disabled={loading}
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
              disabled={loading}
            >
              {loading ? '更新中...' : '更新任务'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
